Thread: [newbie]Find number of times a string appears in another string.

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    2

    [newbie]Find number of times a string appears in another string.

    So I have a parent string hardcoded in to the code.And I have to find number of times a string appears in the original string.I know that I can find the first occurrence of the string using str.find() but how do I start searching the parent string from that position again and update the counter.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    string::find - C++ Reference
    Including an example.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    2
    Here is what I came up with

    Code:
    do {
            pos=str.find("fork",pos);
            count++;
            cout<<"test";
        }while (pos!=string::npos);
    But the loop does not terminate ever.It just prints test repeatedly.What am I doing wrong?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Did you read the link I posted?
    Did you notice a +1 to indicate starting a search at the next character?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 11-05-2012, 03:29 PM
  2. Find first occurance of a number in a string.
    By 337higgin in forum C Programming
    Replies: 8
    Last Post: 09-13-2011, 08:04 AM
  3. Replies: 16
    Last Post: 11-12-2008, 12:02 AM
  4. search number of times a substring apear in a string
    By phoebus in forum C Programming
    Replies: 5
    Last Post: 05-01-2008, 06:36 AM
  5. Character that appears max times in string
    By Roaring_Tiger in forum C Programming
    Replies: 2
    Last Post: 08-15-2004, 12:06 PM

Tags for this Thread